package com.compass.doctor.ui.mine

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import androidx.activity.viewModels
import com.compass.doctor.R
import com.compass.doctor.base.BaseVBActivity
import com.compass.doctor.databinding.ActivityDataStatisticsBinding
import com.compass.doctor.ui.mine.viewmodel.MineViewModel
import com.compass.doctor.utils.ChartUtils
import com.compass.doctor.utils.StringUtils
import com.compass.framework.constant.TIME_YEAR
import com.compass.framework.ext.gone
import com.compass.framework.ext.onClick
import com.compass.framework.ext.visible
import com.compass.framework.model.BusinessProcessing
import com.compass.framework.model.ConsultationType
import com.compass.framework.model.PatientAndFollow
import com.compass.framework.utils.DateUtils
import com.compass.framework.utils.StatusBarSettingHelper
import com.compass.framework.utils.getColorFromResource
import com.github.mikephil.charting.animation.Easing
import com.github.mikephil.charting.data.PieData
import com.github.mikephil.charting.data.PieDataSet
import com.github.mikephil.charting.data.PieEntry
import com.github.mikephil.charting.formatter.PercentFormatter
import com.loper7.date_time_picker.DateTimeConfig
import com.loper7.date_time_picker.dialog.CardDatePickerDialog
import com.loper7.date_time_picker.dialog.CardWeekPickerDialog

/**
 * Description： 数据统计
 * Date:2024/2/4 13:56
 */
class DataStatisticsActivity : BaseVBActivity<ActivityDataStatisticsBinding>() {

    private val colors = intArrayOf(
        Color.rgb(92, 141, 242),//蓝
        Color.rgb(217, 231, 255),//淡蓝
        Color.rgb(254, 104, 151),//粉色
        Color.rgb(118, 202, 121),//绿色
        Color.rgb(246, 78, 50),//红色
        Color.rgb(255, 142, 18)//橘色
    )


    private val animateTime = 1000

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, DataStatisticsActivity::class.java)
            context.startActivity(intent)
        }
    }

//    private lateinit var consultationTypeAdapter: ConsultationTypeAdapter
    private val mineViewModel: MineViewModel by viewModels()
    override fun initView(savedInstanceState: Bundle?) {
        StatusBarSettingHelper.setStatusBarTranslucent(this)
        StatusBarSettingHelper.statusBarLightMode(this@DataStatisticsActivity, true)
        ChartUtils.initPieChart(mBinding.distributionPieChart)
        ChartUtils.initPieChart(mBinding.businessPieChart)
//        consultationTypeAdapter = ConsultationTypeAdapter()
//        mBinding.rcyConsultationType.apply {
//            layoutManager = GridLayoutManager(this@DataStatisticsActivity, 3)
//            adapter = consultationTypeAdapter
//        }


    }

    override fun intListener() {
        mBinding.tvDate.onClick {
            showDateDialog( false)
        }

        mBinding.tvReset.onClick {
            mBinding.tvDate.text="日期筛选"
            mBinding.tvReset.gone()
            getData()
        }
    }

    private var startDate: Long? = null
    private var endDate: Long? = null
    private var recordDate: Long = 0
    private fun showDateDialog( isEnd: Boolean) {
        CardDatePickerDialog.builder(this)
            .setTitle(if (!isEnd) "开始时间" else "结束时间")
            .showBackNow(false)
            .setLabelText("年", "月", "日")
            .setMaxTime(System.currentTimeMillis())
            .setMinTime(if (!isEnd)  System.currentTimeMillis()-TIME_YEAR*10 else recordDate)
            .setBackGroundModel(CardDatePickerDialog.STACK)
            .setDisplayType(DateTimeConfig.YEAR, DateTimeConfig.MONTH, DateTimeConfig.DAY)
            .setThemeColor(getColorFromResource(R.color.color_0165b8))
            .setOnChoose { milliecond ->
                if (isEnd) {
                    var times = StringUtils.conversionTime(
                        recordDate,
                        DateUtils.FORMAT_FOUR
                    ) + "-" + StringUtils.conversionTime(milliecond, DateUtils.FORMAT_FOUR)
                    mBinding.tvDate.text=times
                    startDate=recordDate
                    endDate=milliecond
                    mBinding.tvReset.visible()
                    getData()
                } else {
                    recordDate = milliecond
                    showDateDialog(true)
                }

            }.build().show()
    }

    override fun initData() {

         getData()
        mineViewModel.statisticsLiveData.observe(this) {
            it?.let {
                setBarChatData(it.patientAndFollowStatistics)
                setPieChartData(it.consultationTypeStatistics)
                setBusinessPieChartData(it.businessProcessingStatistics)

            }
            dismissLoading()
        }
    }

    private fun  getData(){
        showLoading()
        mineViewModel.getDataStatistics(startDate,endDate)
    }


    private fun setBarChatData(list: MutableList<PatientAndFollow>) {
        mBinding.chartPlan.animateY(animateTime, Easing.EaseInOutQuad)

        var xAxisValue = ArrayList<String>()
        var patients = ArrayList<Float>()
        var follows = ArrayList<Float>()
        for (index in list.indices) {
            xAxisValue.add(list[index].month)
            patients.add(list[index].relevanceCount)
            follows.add(list[index].followCount)
        }
        ChartUtils.setTwoBarChart(
            mBinding.chartPlan,
            xAxisValue,
            patients,
            follows,
            "新增患者",
            "新增关注"
        )


    }


    private fun setPieChartData(list: MutableList<ConsultationType>) {
//        consultationTypeAdapter.setData(list)
        mBinding.distributionPieChart.setDrawEntryLabels(false)
        mBinding.distributionPieChart.animateY(animateTime, Easing.EaseInOutQuad)

        if (list.isEmpty()) {
            return
        }
        val entries = ArrayList<PieEntry>()
        for (i in list.indices) {
            entries.add(PieEntry(list[i].count.toFloat(), "${list[i].name}  ${list[i].count}"))
        }
        val dataSet = PieDataSet(entries, "")

        dataSet.sliceSpace = 3f
        dataSet.selectionShift = 5f
        dataSet.valueTextSize = 12f
        dataSet.setColors(colors[0], colors[2], colors[3])
        val data = PieData(dataSet)
        data.setValueFormatter(PercentFormatter(mBinding.distributionPieChart))
        data.setValueTextSize(12f)
        data.setValueTextColor(Color.WHITE)
        mBinding.distributionPieChart.data = data
        mBinding.distributionPieChart.invalidate()
    }


    private fun setBusinessPieChartData(list: MutableList<BusinessProcessing>) {
        mBinding.businessPieChart.setDrawEntryLabels(false)
        mBinding.businessPieChart.animateY(animateTime, Easing.EaseInOutQuad)
        if (list.isEmpty()) {
            return
        }
        val entries = ArrayList<PieEntry>()
        for (i in list.indices) {
            entries.add(PieEntry(list[i].count.toFloat(), "${list[i].name}  ${list[i].count}"))
        }
        val dataSet = PieDataSet(entries, "")
        dataSet.sliceSpace = 3f
        dataSet.selectionShift = 5f
        dataSet.valueTextSize = 12f
        dataSet.setColors(colors[0], colors[3], colors[4], colors[5])
        val data = PieData(dataSet)
        data.setValueFormatter(PercentFormatter(mBinding.businessPieChart))
        data.setValueTextSize(12f)
        data.setValueTextColor(Color.WHITE)
        mBinding.businessPieChart.data = data
        mBinding.businessPieChart.invalidate()
    }

}